package com.dingwen.treasure.mongodb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * 　MongoConverterConfig </br>
 *  <pre>
 *      1. 默认使用spring-data向mongo存数据时文档中会自动添加一个_class字段存储实体对象比较占用空间，此处自定义转换器去除
 *  </pre>
 * 　@author dingwen
 * 　@date 2022/6/26
 *
 */
@Configuration(proxyBeanMethods = false)
public class MongoConverterConfig {

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoMappingContext context, MongoCustomConversions conversions) {
        MappingMongoConverter mappingConverter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, context);
        mappingConverter.setCustomConversions(conversions);
        // 去除 _class
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }
}
